package com.example.coffeejava.Controller;

import com.example.coffeejava.Dto.OrderDto;
import com.example.coffeejava.Dto.OrderItemDto;
import com.example.coffeejava.Dto.Result;
import com.example.coffeejava.Entity.Info;
import com.example.coffeejava.Entity.Order;
import com.example.coffeejava.Entity.OrderItem;
import com.example.coffeejava.Entity.UserHolder;
import com.example.coffeejava.Service.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private CartService cartService;
    @Resource
    private ShopService shopService;
@Resource
private InfoService infoService;
    @PostMapping("/add")
    @Transactional
    public Result addorder(@RequestBody OrderDto orderDto) {
        Order order = new Order();
        order.setOrderId(UUID.randomUUID().toString());
        order.setShopId(orderDto.getShopId());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        System.out.println(order.getOrderId()+"orderOd");
        order.setStatus("待发货");
        order.setShopId(orderDto.getShopId());
        order.setUserId(UserHolder.getUser().getId());
        order.setTotalPrice(orderDto.getTotalPrice());
        orderService.save(order);
        List<OrderItemDto> list = orderDto.getList();

        for (OrderItemDto orderItem : list) {
            Info info=infoService.getById(orderItem.getInfoId());
            info.setBuyNum(info.getBuyNum()+orderItem.getNum());
            infoService.updateById(info);
            OrderItem orderItem1 = new OrderItem();
            orderItem1.setInfoId(orderItem.getInfoId());
            orderItem1.setNum(orderItem.getNum());
            orderItem1.setPrice(orderItem.getPrice());
            orderItem1.setOrderId(order.getOrderId());
            orderItemService.save(orderItem1);
            cartService.removeById(orderItem.getCartId());
        }
        return Result.ok("成功");

    }
    @GetMapping("/list")
    public Result list(Integer pageNum,Integer pageSize){
        return orderService.getlist(pageNum,pageSize);
    }
    @GetMapping("/sjlist")
    public Result sjlist(Integer pageNum,Integer pageSize){
        return orderService.getsjlist(pageNum,pageSize);

    }
    @GetMapping("/fh")
    public Result fh(Long id){
        return orderService.fh(id);
    }
    @GetMapping("/sh")
    public Result sh(Long id){
        return orderService.sh(id);
    }
}
